<?php
/**
 * 同城微聚汇
 * ============================================================================
 * 版权所有 2015-2027 武汉鼎联信息技术有限公司，并保留所有权利。
 * 网站地址: http://dlshop.dliansoft.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: 当燃      
 * Date: 2015-09-09
 */

namespace app\admin\controller;
use think\AjaxPage;
use think\Page;
use think\Verify;
use think\Db;
use app\admin\logic\UsersLogic;

class User extends Base {
    public function index(){
        //会员等级
        $levelList = M('user_level')->field('level_id,level_name')->select();
        $this->assign('levelList',$levelList);
        //分销等级
        $distributionList = M('user_level_distribution')->field('level_id,level_name')->select();
        $this->assign('distributionList',$distributionList);
        //门店自提
        $pickList = M('pick_up')->field('pickup_id,pickup_name')->select();
        $this->assign('pickList',$pickList);
        return $this->fetch();
    }

    /**
     * 会员列表
     */
    public function ajaxindex(){
        // 搜索条件
        $condition = array();
        $start_time = strtotime(I('add_time_begin'));
        $over_time = strtotime(I('add_time_end'));
        $name = base64_encode(I('name'));
//        I('mobile') ? $condition['mobile'] = I('mobile') : false;
        I('email') ? $condition['email'] = I('email') : false;
        I('name') ? $condition['nickname'] = array('like','%'.$name.'%') : false;
        I('level') ? $condition['level'] = I('level') : false;
        I('profit') ? $condition['profit_level'] = I('profit') : false;
        I('scene') ? $condition['scene_id'] = I('scene') : false;

        if($start_time && $over_time){
            $condition['reg_time'] = array('between',"$start_time,$over_time");
        }

        if(I('mobile')){
            $condition['mobile'] = I('mobile');
        }else{
            if(I('tel')){
                $condition['mobile'] = array('NEQ','');
            }
        }
        $sort_order = I('order_by','user_id').' '.I('sort','desc');
        $model = M('users');
        $count = $model->where($condition)->count();
        $Page  = new AjaxPage($count,10);
        //  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            if($key == 'reg_time'){
                $between_time = explode(',',$val[1]);
                $parameter_add_time = date('Y/m/d',$between_time[0]) . '-' . date('Y/m/d',$between_time[1]);
                $Page->parameter['timegap'] = $parameter_add_time;
            }elseif($key == 'mobile' && is_array($val)){
                $Page->parameter['mobile'] = '';
            }elseif($key == 'nickname' && is_array($val)) {
                $parameter_name = '%'.$name.'%';
                $Page->parameter['nickname'] = $parameter_name;
            }else{
                $Page->parameter[$key]   =  urlencode($val);
            }

        }
        $userList = $model->where($condition)->order($sort_order)->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $user_id_arr = get_arr_column($userList, 'user_id');
        

        if(!empty($user_id_arr))
        {
            $first_leader = DB::query("select first_leader,count(1) as count  from __PREFIX__users where first_leader in(".  implode(',', $user_id_arr).")  group by first_leader");
            $first_leader = convert_arr_key($first_leader,'first_leader');

            $second_leader = DB::query("select second_leader,count(1) as count  from __PREFIX__users where second_leader in(".  implode(',', $user_id_arr).")  group by second_leader");
            $second_leader = convert_arr_key($second_leader,'second_leader');

            $third_leader = DB::query("select third_leader,count(1) as count  from __PREFIX__users where third_leader in(".  implode(',', $user_id_arr).")  group by third_leader");
            $third_leader = convert_arr_key($third_leader,'third_leader');
        }
        //门店自提
        $pickList = M('pick_up')->field('pickup_id,pickup_name')->select();
        foreach($userList as $k=>$v){
            $pick = M('pick_up')->field('pickup_name')->where('pickup_id',$v['scene_id'])->find();
            $userList[$k]['pickup_name'] = $pick['pickup_name'];
            if($v['scene_id'] == '0'){
                $userList[$k]['scene_id'] = '总店';
            }
        }
        $this->assign('pickList',$pickList);
        $this->assign('first_leader',$first_leader);
        $this->assign('second_leader',$second_leader);
        $this->assign('third_leader',$third_leader);                                
        $show = $Page->show();
        $this->assign('userList',$userList);
        $this->assign('level',M('user_level')->getField('level_id,level_name'));
        $this->assign('profitLevel',M('user_level_distribution')->getField('level_id,level_name'));
        $this->assign('page',$show);// 赋值分页输出
        $this->assign('pager',$Page);
        return $this->fetch();
    }

    /**
     * 会员详细信息查看
     */
    public function detail(){
        $uid = I('get.id');
        $user = D('users')->where(array('user_id'=>$uid))->find();
        if(!$user)
            exit($this->error('会员不存在'));
        if(IS_POST){
            //  会员信息编辑
            $password = I('post.password');
            $password2 = I('post.password2');
            if($password != '' && $password != $password2){
                exit($this->error('两次输入密码不同'));
            }
            if($password == '' && $password2 == ''){
                unset($_POST['password']);
            }else{
                $_POST['password'] = encrypt($_POST['password']);
            }

            if(!empty($_POST['email']))
            {   $email = trim($_POST['email']);
                $c = M('users')->where("user_id != $uid and email = '$email'")->count();
                $c && exit($this->error('邮箱不得和已有用户重复'));
            }            
            
            if(!empty($_POST['mobile']))
            {   $mobile = trim($_POST['mobile']);
                $c = M('users')->where("user_id != $uid and mobile = '$mobile'")->count();
                $c && exit($this->error('手机号不得和已有用户重复'));
            }            
            if(!empty($_POST['profit_level']))
            {
                $distribution = M('user_level_distribution')->find($_POST['profit_level']);
                $_POST['profit_amount'] = $distribution['amount'];
            }
            $row = M('users')->where(array('user_id'=>$uid))->save($_POST);
            if($row)
                exit($this->success('修改成功'));
            exit($this->error('未作内容修改或修改失败'));
        }
        
        $user['first_lower'] = M('users')->where("first_leader = {$user['user_id']}")->count();
        $user['second_lower'] = M('users')->where("second_leader = {$user['user_id']}")->count();
        $user['third_lower'] = M('users')->where("third_leader = {$user['user_id']}")->count();
        $this->assign('profitLevel',M('user_level_distribution')->field('level_id,level_name')->select());
        $this->assign('user',$user);
        return $this->fetch();
    }
    
    public function add_user(){
    	if(IS_POST){
    		$data = I('post.');
            if($data['profit_level'] != '1'){
                $distribution = M('user_level_distribution')->find($data['profit_level']);
                $data['profit_amount'] = $distribution['amount'];
            }
			$user_obj = new UsersLogic();
			$res = $user_obj->addUser($data);
			if($res['status'] == 1){
				$this->success('添加成功',U('User/index'));exit;
			}else{
				$this->error('添加失败,'.$res['msg'],U('User/index'));
			}
    	}
        $this->assign('profit',M('user_level_distribution')->field('level_id,level_name')->select());
    	return $this->fetch();
    }

    /**
     * 用户收货地址查看
     */
    public function address(){
        $uid = I('get.id');
        $lists = D('user_address')->where(array('user_id'=>$uid))->select();
        $regionList = M('Region')->getField('id,name');
        $this->assign('regionList',$regionList);
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    /**
     * 删除会员
     */
    public function delete(){
        $uid = I('get.id');
        $row = M('users')->where(array('user_id'=>$uid))->delete();
        if($row){
            $this->success('成功删除会员');
        }else{
            $this->error('操作失败');
        }
    }
    /**
     * 删除会员
     */
    public function ajax_delete(){
        $uid = I('id');
        if($uid){
            $row = M('users')->where(array('user_id'=>$uid))->delete();
            if($row !== false){
                $this->ajaxReturn(array('status' => 1, 'msg' => '删除成功', 'data' => ''));
            }else{
                $this->ajaxReturn(array('status' => 0, 'msg' => '删除失败', 'data' => ''));
            }
        }else{
            $this->ajaxReturn(array('status' => 0, 'msg' => '参数错误', 'data' => ''));
        }
    }

    /**
     * 账户资金记录
     */
    public function account_log(){
        $user_id = I('get.id');
        //获取类型
        $type = I('get.type');
        //获取记录总数
        $count = M('account_log')->where(array('user_id'=>$user_id))->count();
        $page = new Page($count);
        $lists  = M('account_log')->where(array('user_id'=>$user_id))->order('change_time desc')->limit($page->firstRow.','.$page->listRows)->select();

        $this->assign('user_id',$user_id);
        $this->assign('page',$page->show());
        $this->assign('lists',$lists);
        return $this->fetch();
    }

    /**
     * 账户资金调节
     */
    public function account_edit(){
        $user_id = I('get.id');
        if(!$user_id > 0)
            $this->error("参数有误");
        if(IS_POST){
            //获取操作类型
            $m_op_type = I('post.money_act_type');
            $user_money = I('post.user_money/f');
            $user_money =  $m_op_type ? $user_money : 0-$user_money;

            $p_op_type = I('post.point_act_type');
            $pay_points = I('post.pay_points/d');
            $pay_points =  $p_op_type ? $pay_points : 0-$pay_points;

            $f_op_type = I('post.frozen_act_type');
            $frozen_money = I('post.frozen_money/f');
            $frozen_money =  $f_op_type ? $frozen_money : 0-$frozen_money;

            $desc = I('post.desc');
            if(!$desc)
                $this->error("请填写操作说明");
            if(accountLog($user_id,$user_money,$pay_points,$desc)){
                $this->success("操作成功",U("Admin/User/account_log",array('id'=>$user_id)));
            }else{
                $this->error("操作失败");
            }
            exit;
        }
        $this->assign('user_id',$user_id);
        return $this->fetch();
    }
    
    public function recharge(){
    	$timegap = I('timegap');
    	$nickname = I('nickname');
    	$map = array();
    	if($timegap){
    		$gap = explode(' - ', $timegap);
    		$begin = $gap[0];
    		$end = $gap[1];
    		$map['ctime'] = array('between',array(strtotime($begin),strtotime($end)));
    	}
    	if($nickname){
    		$map['nickname'] = array('like',"%$nickname%");
    	}  	
    	$count = M('recharge')->where($map)->count();
    	$page = new Page($count);
    	$lists  = M('recharge')->where($map)->order('ctime desc')->limit($page->firstRow.','.$page->listRows)->select();
    	$this->assign('page',$page->show());
        $this->assign('pager',$page);
    	$this->assign('lists',$lists);
    	return $this->fetch();
    }
    
    public function level(){
    	$act = I('get.act','add');
    	$this->assign('act',$act);
    	$level_id = I('get.level_id');
    	$level_info = array();
    	if($level_id){
    		$level_info = D('user_level')->where('level_id='.$level_id)->find();
    		$this->assign('info',$level_info);
    	}
    	return $this->fetch();
    }
    
    public function levelList(){
    	$Ad =  M('user_level');
        $p = $this->request->param('p');
    	$res = $Ad->where('1=1')->order('level_id')->page($p.',10')->select();
    	if($res){
    		foreach ($res as $val){
    			$list[] = $val;
    		}
    	}
    	$this->assign('list',$list);
    	$count = $Ad->where('1=1')->count();
    	$Page = new Page($count,10);
    	$show = $Page->show();
    	$this->assign('page',$show);
    	return $this->fetch();
    }
    
    public function levelHandle(){
    	$data = I('post.');
    	if($data['act'] == 'add'){
    		$r = D('user_level')->add($data);
    	}
    	if($data['act'] == 'edit'){
    		$r = D('user_level')->where('level_id='.$data['level_id'])->save($data);
    	}
    	 
    	if($data['act'] == 'del'){
    		$r = D('user_level')->where('level_id='.$data['level_id'])->delete();
    		if($r) exit(json_encode(1));
    	}
    	 
    	if($r){
    		$this->success("操作成功",U('Admin/User/levelList'));
    	}else{
    		$this->error("操作失败",U('Admin/User/levelList'));
    	}
    }

    /**
     * 搜索用户名
     */
    public function search_user()
    {
        $search_key = trim(I('search_key'));        
        if(strstr($search_key,'@'))    
        {
            $list = M('users')->where(" email like '%$search_key%' ")->select();        
            foreach($list as $key => $val)
            {
                echo "<option value='{$val['user_id']}'>{$val['email']}</option>";
            }                        
        }
        else
        {
            $list = M('users')->where(" mobile like '%$search_key%' ")->select();        
            foreach($list as $key => $val)
            {
                echo "<option value='{$val['user_id']}'>{$val['mobile']}</option>";
            }            
        } 
        exit;
    }
    
    /**
     * 分销树状关系
     */
    public function ajax_distribut_tree()
    {
          $list = M('users')->where("first_leader = 1")->select();
          return $this->fetch();
    }

    /**
     *
     * @time 2016/08/31
     * @author dyr
     * 发送站内信
     */
    public function sendMessage()
    {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $users = M('users')->field('user_id,nickname')->where(array('user_id' => array('IN', $user_id_array)))->select();
        }
        $this->assign('users',$users);
        return $this->fetch();
    }

    /**
     *
     * @time 2016/08/31
     * @author dyr
     * 发送微信文字消息或者图文消息
     */
    public function sendtxtmsg()
    {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $users = M('users')->field('user_id,nickname')->where(array('user_id' => array('IN', $user_id_array)))->select();
        }
        $this->assign('users',$users);
        $this->assign('user_id_array',$user_id_array);
        return $this->fetch();
    }
    public function doSendtxtmsg(){
        $user_id_array = I('post.user_id_array');
        $users=explode(',', $user_id_array);
        $tplarr=array(
            'title'=>'你有一份约“惠”快乐的机会，速来领取！',
            'description'=>' 有时有点小失落，有时有点小沮丧，有时有点不开森。',
            'url'=>'http://mp.weixin.qq.com/s/el2S8GDM3DYseyVtWQnw7w',
            'picurl'=>'https://mmbiz.qlogo.cn/mmbiz_png/jpC9tQduIEZ2BdrmSVHxZoxTwZoBXUoias4WiaYBicbfQiawWKCzC4dQdID7FCXKXhhmQxOPcQ1RzrnfmmrpcDkF2w/0?wx_fmt=png',
            );
        foreach ($users as $key => $value) {
            push_wxmessage($value, $tplarr,'news');
        }
        
    }
    public function getuserlist(){
        $count = M('users')->count();
        $Page  = new Page($count,100);
        $list = M('users')->order("`user_id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        if($list){
            echo implode(',', $list);
        }else{
            echo 0;
        }
        
    }
     /**
     *
     * @time 2017/05/03
     * @author hongi
     * 发送微信模板消息
     */
    public function sendwxMessage()
    {
        $wid = I('get.wid');
        $users = M('wx_template_msg')->field('user_list,send_area,link,content,send_time')->where(array('id' => $wid))->find();
        if(!empty($users['send_time'])){
            $wx_template_msg_list=M('wx_template_msg_list');
            $faillist=$wx_template_msg_list->field('t_id,to_member,status')->where(array('t_id' => $wid,'status'=>'fail'))->select();
            $this->assign('faillist',$faillist);
        }
        $this->assign('users',$users);
        $this->assign('wid',$wid);

        return $this->fetch();
    }

    
    /**
     * 发送系统消息
     * @author dyr
     * @time  2016/09/01
     */
    public function doSendMessage()
    {
        $call_back = I('call_back');//回调方法
        $text= I('post.text');//内容
        $type = I('post.type', 0);//个体or全体
        $admin_id = session('admin_id');
        $users = I('post.user/a');//个体id
        $message = array(
            'admin_id' => $admin_id,
            'message' => $text,
            'category' => 0,
            'send_time' => time()
        );

        if ($type == 1) {
            //全体用户系统消息
            $message['type'] = 1;
            M('Message')->add($message);
        } else {
            //个体消息
            $message['type'] = 0;
            if (!empty($users)) {
                $create_message_id = M('Message')->add($message);
                foreach ($users as $key) {
                    M('user_message')->add(array('user_id' => $key, 'message_id' => $create_message_id, 'status' => 0, 'category' => 0));
                }
            }
        }
        echo "<script>parent.{$call_back}(1);</script>";
        exit();
    }
    //发送微信消息
     public function doSendwxMessage()
    {
        $call_back = I('call_back');//回调方法
        $wid = I('get.wid');
        $tpltext= I('post.tpltext');//内容
        $type = I('post.type', 0);//个体or全体
        $admin_id = session('admin_id');
        $users = I('post.user/a');//个体id
        $href = I('post.url', '/mobile/');
        if($type == 0){
            $mobile= I('post.mobile');
            if($mobile){
                if(strpos($mobile,'u')>-1){
                    $where['user_id']=str_replace('u','',$mobile);
                }else{
                    $where['mobile']=$mobile;
                }
                $users=M('users')->field('user_id,nickname,reg_time,appid,openid,oauth')->where($where)->find();
            }
        }

            if(!empty($users)){
               $result=push_wxtplmessage_admin($users,$tpltext,$href);//发送消息
              $data['to_member']=base64_encode($users['user_id'].':'.shownickname($users['nickname']));
            }else{
                $result['errmsg']='fail';
                $result['errcode']='用户不存在';
                $data['to_member']=$mobile;
            }

        if($result['errmsg']=="ok"){
          $data['status']="ok";
        }else{
          $data['status']="fail";
        }

        $data['t_id']=$wid;
        $data['error_log']=$result['errcode'];
        M('wx_template_msg_list')->add($data);
        echo json_encode($result);
        //echo "<script>parent.{$call_back}(1);</script>";
        exit();
    }
    /*统计发送的微信消息*/
    public function count_wxmessage(){
        $wid=I('post.wid');
        $succ=I('post.succ');
        $fail=I('post.fail');
        $count_mess=M('wx_template_msg_list')->where('t_id',$wid)->count();
        $data['success_num']=$succ;
        $data['fail_num']=$fail;
        $data['send_time']=time();
        M('wx_template_msg')->where('id',$wid)->save($data);
        echo date('Y-m-d',$data['send_time']);
    }

    /**
     *
     * @time 2016/09/03
     * @author dyr
     * 发送邮件
     */
    public function sendMail()
    {
        $user_id_array = I('get.user_id_array');
        $users = array();
        if (!empty($user_id_array)) {
            $user_where = array(
                'user_id' => array('IN', $user_id_array),
                'email' => array('neq', '')
            );
            $users = M('users')->field('user_id,nickname,email')->where($user_where)->select();
        }
        $this->assign('smtp', tpCache('smtp'));
        $this->assign('users', $users);
        return $this->fetch();
    }

    /**
     * 发送邮箱
     * @author dyr
     * @time  2016/09/03
     */
    public function doSendMail()
    {
        $call_back = I('call_back');//回调方法
        $message = I('post.text');//内容
        $title = I('post.title');//标题
        $users = I('post.user/a');
        if (!empty($users)) {
            $user_id_array = implode(',', $users);
            $users = M('users')->field('email')->where(array('user_id' => array('IN', $user_id_array)))->select();
            $to = array();
            foreach ($users as $user) {
                if (check_email($user['email'])) {
                    $to[] = $user['email'];
                }
            }
            $res = send_email($to, $title, $message);
            echo "<script>parent.{$call_back}({$res});</script>";
            exit();
        }
    }

    /**
     * 提现申请记录
     */
    public function withdrawals()
    {
        $model = M("withdrawals");
        $_GET = array_merge($_GET,$_POST);
        unset($_GET['create_time']);

        $status = I('status');
        $user_id = I('user_id');
        $account_bank = I('account_bank');
        $account_name = I('account_name');
        $create_time = I('create_time');
        $create_time = $create_time  ? $create_time  : date('Y/m/d',strtotime('-1 year')).'-'.date('Y/m/d',strtotime('+1 day'));
        $create_time2 = explode('-',$create_time);
        $this->assign('start_time', $create_time2[0]);
        $this->assign('end_time', $create_time2[1]);
        $where = " create_time >= '".strtotime($create_time2[0])."' and create_time <= '".strtotime($create_time2[1])."' ";

        if($status === '0' || $status > 0)
        $where .= " and status = $status ";
        $user_id && $where .= " and user_id = $user_id ";
        $account_bank && $where .= " and account_bank like '%$account_bank%' ";
        $account_name && $where .= " and account_name like '%$account_name%' ";

        $count = $model->where($where)->count();
        $Page  = new Page($count,16);
        $list = $model->where($where)->order("`id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();

        $this->assign('create_time',$create_time);
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('pager',$Page);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        return $this->fetch();
    }
    /**
     * 删除申请记录
     */
    public function delWithdrawals()
    {
        $model = M("withdrawals");
        $model->where('id ='.$_GET['id'])->delete();
        $return_arr = array('status' => 1,'msg' => '操作成功','data'  =>'',);   //$return_arr = array('status' => -1,'msg' => '删除失败','data'  =>'',);
        $this->ajaxReturn($return_arr);
    }

    /**
     * 修改编辑 申请提现
     */
    public function editWithdrawals()
    {
        $id = I('id');
        $withdrawals = DB::name('withdrawals')->where('id',$id)->find();
        $user_id = M('users')->where("user_id = {$withdrawals[user_id]}")->find();
        if (IS_POST) {
            $data = I('post.');
            // 如果是已经给用户转账 则生成转账流水记录
            if ($data['status'] == 1 && $withdrawals['status'] != 1) {
                if ($user_id['user_money'] < $withdrawals['money']) {
                    $this->error("用户余额不足{$withdrawals['money']}，不够提现");
                    exit;
                }
//                accountLog($withdrawals['user_id'], ($withdrawals['money'] * -1), 0, "平台提现");
                $remittance = array(
                    'user_id' => $withdrawals['user_id'],
                    'bank_name' => $withdrawals['bank_name'],
                    'account_bank' => $withdrawals['account_bank'],
                    'account_name' => $withdrawals['account_name'],
                    'money' => $withdrawals['money'],
                    'status' => 1,
                    'create_time' => time(),
                    'admin_id' => session('admin_id'),
                    'withdrawals_id' => $withdrawals['id'],
                    'remark' => $data['remark'],
                );
                M('remittance')->add($remittance);
            }
            //微信提现
            $user = M('users')->where(array('user_id' => $withdrawals['user_id']))->find();
            if ($user['user_money'] < $withdrawals['money']) {
                $data['status'] = -2;
                $data['remark'] = '账户余额不足';
                M('withdrawals')->where(array('id' => $withdrawals['id']))->save($data);
            } else {
                if ($withdrawals['bank_name'] = '微信') {
                    $wxpay = array(
                        'userid' => $withdrawals['user_id'],//用户ID做更新状态使用
                        'openid' => $withdrawals['account_bank'],//收钱的人微信 OPENID
                        'money' => $withdrawals['money'],//金额
                        'desc' => '您申请的提现已经到账【微信钱包-零钱】，请注意查收!'
                    );
                    $res = $this->transfer('weixin', $wxpay);//微信在线付款转账
                    $res=json_decode(json_encode($res),true);
  
                    if ($res['partner_trade_no']) {
                        if($res['status']=="SUCCESS"){
                            accountLog($withdrawals['user_id'], ($withdrawals['money'] * -1), 0, "平台处理用户提现申请");
                            $r = M('withdrawals')->where(array('id' => $withdrawals['id']))->save(array('status' => '1', 'pay_time' => time()));
                            $this->success("操作成功!", U('Admin/User/remittance'), 3);
                        }
                        if($res['status']=="FAIL"){
                            $msg=$res['reason'];
                        }
                    }else{
                        $msg=$res['err_code_des'];
                    } 

                    $this->error("操作失败!".$msg);
                }
            }
            
            DB::name('withdrawals')->where('id',$id)->update($data);
            exit;
        }

        if ($user_id['nickname'])
            $withdrawals['user_name'] = $user_id['nickname'];
        elseif ($user_id['email'])
            $withdrawals['user_name'] = $user_id['email'];
        elseif ($user_id['mobile'])
            $withdrawals['user_name'] = $user_id['mobile'];
        $this->assign('user', $user_id);
        $this->assign('data', $withdrawals);
        return $this->fetch();
    }

    public function withdrawals_update(){
        $id = I('id/a');
        $status = I('status');
        $withdrawals = M('withdrawals')->where('id','in', $id)->select();
        if($status == 1){
            $r = M('withdrawals')->where('id','in', $id)->save(array('status'=>$status,'check_time'=>time()));
        }else if($status == -1){
            $r = M('withdrawals')->where('id','in', $id)->save(array('status'=>$status,'refuse_time'=>time()));
        }else if($status == '2'){
            foreach($withdrawals as $val){
                $user = M('users')->where(array('user_id'=>$val['user_id']))->find();
                if($user['distribut_money'] < $val['money'])
                {
                    $data['status'] = -2;
                    $data['remark'] = '账户余额不足';
                    M('withdrawals')->where(array('id'=>$val['id']))->save($data);
                }else{
                    if($val['bank_name'] = '支付宝 '){
                        //流水号1^收款方账号1^收款账号姓名1^付款金额1^备注说明1|流水号2^收款方账号2^收款账号姓名2^付款金额2^备注说明2
                        $alipay['batch_no'] = time();
                        $alipay['batch_fee'] += $val['money'];
                        $alipay['batch_num'] += 1;
                        $str = isset($alipay['detail_data']) ? '|' : '';
                        $alipay['detail_data'] .= $str.$val['pay_code'].'^'.$val['account_bank'].'^'.$val['realname'].'^'.$val['money'].'^'.$val['remark'];
                    }
                    if($val['bank_name'] = '微信'){
                        $wxpay = array(
                            'userid' => $val['user_id'],//用户ID做更新状态使用
                            'openid' => $val['account_bank'],//收钱的人微信 OPENID
                            'pay_code'=>$val['pay_code'],//提现申请ID
                            'money' => $val['money'],//金额
                            'desc' => '恭喜您提现申请成功!'
                        );
                        $res = $this->transfer('weixin',$wxpay);//微信在线付款转账
                        die();
                        if($res['partner_trade_no']){
                            accountLog($val['user_id'], ($val['money'] * -1), 0,"平台处理用户提现申请");
                            $r = M('withdrawals')->where(array('id'=>$val['id']))->save(array('status'=>$status,'pay_time'=>time()));
                        }else{
                            $this->ajaxReturn(array('status'=>0,'msg'=>$res['msg']),'JSON');
                        }
                    }
                }
            }
            if(!empty($alipay)){
                $this->transfer('alipay',$alipay);
            }
            $this->ajaxReturn(array('status'=>1,'msg'=>"操作成功"),'JSON');
        }else if($status == 3){
            $r = M('withdrawals')->where('id in ('.implode(',', $id).')')->delete();
        }else{
            accountLog($val['user_id'], ($val['money'] * -1), 0,"管理员处理用户提现申请");//手动转账，默认视为已通过线下转方式处理了该笔提现申请
            $r = M('withdrawals')->where('id in ('.implode(',', $id).')')->save(array('status'=>2,'pay_time'=>time()));
        }
        if($r){
            $this->ajaxReturn(array('status'=>1,'msg'=>"操作成功"),'JSON');
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>"操作失败"),'JSON');
        }

    }

    public function transfer($atype,$data){
        if($atype == 'weixin'){
            include_once  PLUGIN_PATH."payment/weixin/company.class.php";
            $wxpay_obj = new \company();
            return $wxpay_obj->transfer($data);
        }else{
            //支付宝在线批量付款
            include_once  PLUGIN_PATH."payment/alipay/alipay.class.php";
            $alipay_obj = new \alipay();
            return $alipay_obj->transfer($data);
        }
    }
    /**
     *  转账汇款记录
     */
    public function remittance(){
        $model = M("remittance");
        $_GET = array_merge($_GET,$_POST);
        unset($_GET['create_time']);

        $user_id = I('user_id');
        $account_bank = I('account_bank');
        $account_name = I('account_name');

        $create_time = I('create_time');
        $create_time = $create_time  ? $create_time  : date('Y-m-d',strtotime('-1 year')).' - '.date('Y-m-d',strtotime('+1 day'));
        $create_time2 = explode(' - ',$create_time);
        $this->assign('start_time',$create_time2[0]);
        $this->assign('end_time',$create_time2[1]);
        $where = " create_time >= '".strtotime($create_time2[0])."' and create_time <= '".strtotime($create_time2[1])."' ";
        $user_id && $where .= " and user_id = $user_id ";
        $account_bank && $where .= " and account_bank like '%$account_bank%' ";
        $account_name && $where .= " and account_name like '%$account_name%' ";

        $count = $model->where($where)->count();
        $Page  = new Page($count,16);
        $list = $model->where($where)->order("`id` desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('pager',$Page);
        $this->assign('create_time',$create_time);
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('list',$list);
        C('TOKEN_ON',false);
        return $this->fetch();
    }


    /*
     * 分销等级列表
     */
    public function distributionList()
    {
        $Ad =  M('user_level_distribution');
        $p = $this->request->param('p');
        $res = $Ad->where('1=1')->order('level_id')->page($p.',10')->select();
        if($res){
            foreach ($res as $val){
                $list[] = $val;
            }
        }
        $this->assign('list',$list);
        $count = $Ad->where('1=1')->count();
        $Page = new Page($count,10);
        $show = $Page->show();
        $this->assign('page',$show);
        return $this->fetch();
    }


    /*
     * 添加分销等级页面
     */
    public function distribution()
    {
        $act = I('get.act','add');
        $this->assign('act',$act);
        $level_id = I('get.level_id');
        $level_info = array();
        if($level_id){
            $level_info = D('user_level_distribution')->where('level_id='.$level_id)->find();
            $this->assign('info',$level_info);
        }
        return $this->fetch();
    }


    /*
     * 添加分销等级
     */
    public function distributionHandle()
    {
        $data = I('post.');
        if($data['act'] == 'add'){
            $r = D('user_level_distribution')->add($data);
        }
        if($data['act'] == 'edit'){
            $r = D('user_level_distribution')->where('level_id='.$data['level_id'])->save($data);
        }

        if($data['act'] == 'del'){
            $r = D('user_level_distribution')->where('level_id='.$data['level_id'])->delete();
            if($r) exit(json_encode(1));
        }

        if($r){
            $this->success("操作成功",U('Admin/User/distributionList'));
        }else{
            $this->error("操作失败",U('Admin/User/distributionList'));
        }
    }
    /*
     * 代理商等级列表
     */
    public function agent_level()
    {
        $p = $this->request->param('p');
        $agent_id=M('admin')->where('admin_id',session('admin_id'))->getField('agent_id');
        $res = M('agent_level')->where(['agent_id'=>$agent_id])->order('level_id')->page($p.',10')->select();
        if($res){
            foreach ($res as $val){
                $list[] = $val;
            }
        }
  
        $this->assign('list',$list);
        $count = M('agent_level')->where('1=1')->count();
        $Page = new Page($count,10);
        $show = $Page->show();
        $this->assign('page',$show);
        return $this->fetch();
    }
     /*
     * 添加代理商等级页面
     */
    public function agent_level_info()
    {
        $act = I('get.act','add');
        $this->assign('act',$act);
        $level_id = I('get.level_id');
        $level_info = array();
        if($level_id){
            $level_info = D('agent_level')->where('level_id='.$level_id)->find();
            $this->assign('info',$level_info);
        }
        return $this->fetch();
    }
    /*
     * 添加代理商等级
     */
    public function agentHandle()
    {
        $data = I('post.');
        $data['agent_id']=M('admin')->where(['admin_id'=>session('admin_id')])->getField('agent_id');

        if($data['act'] == 'add'){
            $r = D('agent_level')->add($data);
        }
        if($data['act'] == 'edit'){
            $r = D('agent_level')->where('level_id='.$data['level_id'])->save($data);
        }

        if($data['act'] == 'del'){
            $r = D('agent_level')->where('level_id='.$data['level_id'])->delete();
            if($r) exit(json_encode(1));
        }

        if($r){
            $this->success("操作成功",U('Admin/User/agent_level'));
        }else{
            $this->error("操作失败",U('Admin/User/agent_level'));
        }
    }
    /*
     * 代理商/供应商-我的账户
     */
    public function myaccount()
    {
         
         $list=M('agent_account_log a')->field('a.*,b.order_sn,b.goods_price,b.order_amount,b.user_money,c.goods_price as good_price,c.goods_num')->join('tp_order b','a.order_id=b.order_id','left')->join('tp_order_goods c','a.rec_id=c.rec_id','left')->where('a.agent_id',session('agent_id'))->select();
         $agent=M('agents')->field('agent_id')->where('parent_id',session('agent_id'))->select();

         if($agent){
            foreach ($agent as $key => $value) {
                $agentlist[]=$value['agent_id'];
            }
             $agent_arr_in=implode(',',$agentlist);
             $where['a.agent_id']=array('in',$agent_arr_in);
             $a_list=M('agent_account_log a')->field('a.*,b.order_sn,b.goods_price,b.order_amount,b.user_money')->join('tp_order b','a.order_id=b.order_id','left')->where($where)->select();
             foreach ($a_list as $key => $value) {
                $alist[$value['order_id']]=$value;
            }
            $is_agent=1;
         }else{
            $is_agent=0;
         }
          $is_in_arr=array();
          foreach ($list as $key => $value) {
            if($is_agent==1){
               $value['agent_money']=bcmul($alist[$value['order_id']]['money'],1,2);//每种商品代理商收益
             }
             $value['payables']=bcadd($value['order_amount'], $value['user_money'],2);//应付金额
             $value['good_prices']=bcmul($value['good_price'],$value['goods_num'],2);
             $k=array_search($value['order_sn'], $is_in_arr);
             if($k>-1){
                 $mlist[$k]['good_prices']=bcadd($mlist[$k]['good_prices'], $value['good_prices'],2);
                 $mlist[$k]['money']=bcadd($mlist[$k]['money'], $value['money'],2);
             }else{
                 $is_in_arr[$key]=$value['order_sn'];
                 $mlist[$key]=$value;
             } 
         }

         $user_money=M('agent_account_log')->where('agent_id',session('agent_id'))->sum('money');
        

         $this->assign('list',$mlist);
         $this->assign('alist',$alist);
         $this->assign('user_money',$user_money);
         $this->assign('is_agent',$is_agent);
         return $this->fetch();
    }
    //代理商收益商品详情
    public function agent_saleList(){
            $order_id=I('order_id');

            $order_goods=M('agent_account_log a')->join('tp_order_goods b','a.rec_id=b.rec_id','left')->where(['a.order_id'=>$order_id])->select();

            $agent_ids=M('agents')->where('parent_id',session('agent_id'))->select();
            
            if($agent_ids){
                 foreach ($agent_ids as $key => $value) {
                    $agentlist[]=$value['agent_id'];
                }

                foreach ($order_goods as $key => $value) {
                    if(in_array($value['agent_id'], $agentlist)){
                         $mlist[$value['order_id'].$value['rec_id']]['agent_money']=$value['money'];
                    }else{
                         $mlist[$value['order_id'].$value['rec_id']]=$value;
                    }
                    
                   
                }

            }

            $this->assign('order_goods',$mlist);

            return $this->fetch();
    }
}